﻿using System;
using System.Collections.ObjectModel;
using System.Xml;

namespace Graphe.Collations
{
    public class VerseCollection : ObservableCollection<Verse>, ICollationElement, IComparable<VerseCollection>
    {
        #region ICollationElement Members

        public void Parse(XmlReader reader, CollationDebugMessages debugMessages)
        {
            using (XmlReader subReader = reader.ReadSubtree())
            {
                while (subReader.ReadToFollowing("Verse"))
                {
                    using (XmlReader verseReader = subReader.ReadSubtree())
                    {
                        Verse verse = new Verse();
                        verse.Parse(subReader, debugMessages);
                        Add(verse);
                    }
                }
            }
        }

        public void Render(XmlTextWriter writer)
        {
            writer.WriteStartElement("Verses");
            foreach (Verse verse in this)
                verse.Render(writer);
            writer.WriteEndElement();
        }

        #endregion
        #region IComparable<VerseCollection> Members

        public int CompareTo(VerseCollection other)
        {
            if (Count != other.Count)
                return -1;

            foreach (Verse verse in this)
            {
                bool foundMatch = false;

                foreach (Verse verse2 in other)
                {
                    if (verse.CompareTo(verse2) == 0)
                    {
                        foundMatch = true;
                        break;
                    }
                }

                if (!foundMatch)
                    return -1;
            }

            foreach (Verse verse in other)
            {
                bool foundMatch = false;

                foreach (Verse verse2 in this)
                {
                    if (verse.CompareTo(verse2) == 0)
                    {
                        foundMatch = true;
                        break;
                    }
                }

                if (!foundMatch)
                    return -1;
            }

            return 0;
        }

        #endregion
    }
}
